package timer

import (
	"encoding/json"
	"time"
)

type recordTimer struct {
	Key       string
	TimerType Type
	Delay     time.Duration
	Data      []byte
}

type recordManager struct {
	Timer map[string]*recordTimer
}

func (g *TimerManager) MarshalJSON() ([]byte, error) {
	ret := &recordManager{
		Timer: make(map[string]*recordTimer),
	}
	for key, tr := range g.timersMap {
		record := tr.ToRecord()
		if record == nil {
			continue
		}
		ret.Timer[key] = record
	}
	return json.Marshal(ret)
}

func (g *TimerManager) UnmarshalJSON(data []byte) error {
	ret := &recordManager{}
	err := json.Unmarshal(data, ret)
	if err != nil {
		return err
	}
	for k, v := range ret.Timer {
		err := g.addTimerFromStore(v)
		if err != nil {
			g.Errorf(k, "recover timer error %+v", err)
			continue
		}
	}
	return nil
}
